package com.edu.controller;

import com.edu.entity.Teacher;
import com.edu.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @GetMapping("/list")
    public String listTeachers(Model model) {
        model.addAttribute("teachers", teacherService.findAll());
        return "teacher/list";
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("teacher", new Teacher());
        return "teacher/form";
    }

    @PostMapping("/save")
    public String saveTeacher(@ModelAttribute Teacher teacher) {
        teacherService.save(teacher);
        return "redirect:/teacher/list";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Integer id, Model model) {
        model.addAttribute("teacher", teacherService.findById(id));
        return "teacher/form";
    }

    @GetMapping("/delete/{id}")
    public String deleteTeacher(@PathVariable Integer id) {
        teacherService.delete(id);
        return "redirect:/teacher/list";
    }

    @GetMapping("/search")
    public String searchTeachers(@RequestParam String keyword, Model model) {
        model.addAttribute("teachers", teacherService.search(keyword));
        return "teacher/list";
    }
}